<%@page import="org.joda.time.DateTime"%>
<%@page import="java.util.*, 
  blackboard.platform.session.*, 
  blackboard.persist.*,
  blackboard.data.user.*, 
  blackboard.persist.user.*, 
  blackboard.data.course.*, 
  blackboard.persist.course.*,
  blackboard.portal.external.*,
  java.io.IOException,
  java.io.OutputStream,
  java.net.HttpURLConnection,
  java.net.URL,
  java.io.InputStream,
  java.io.InputStreamReader,
  java.util.Iterator,
  org.json.simple.JSONArray,
  org.json.simple.JSONObject,
  org.json.simple.parser.JSONParser,
  org.joda.time.format.ISODateTimeFormat,
  org.joda.time.format.DateTimeFormatter,
  com.ocpsoft.pretty.time.PrettyTime" 
errorPage="/error.jsp"
%>
<%@ taglib uri="/bbUI" prefix="bbUI"%>
<%@ taglib uri="/bbNG" prefix="bbNG"%>
<%@ taglib uri="/bbData" prefix="bbData"%>
<bbData:context id="ctx">
<%

String aspireLink = null;

User sessionUser = ctx.getUser(); 
String sessionUserName = sessionUser.getUserName(); 
Id sessionUserId = sessionUser.getId();

try
{
	//Get a User instance via user context
	
	Course sessionCourse = ctx.getCourse();
	String sessionCourseId = sessionCourse.getCourseId();

	CustomData cd = CustomData.getModuleData(pageContext);
	String aspireBaseUrl = cd.getValue("aspireBaseUrl");
	String targetKg = cd.getValue("targetNodeType");
	String regex = cd.getValue("regexCourseId");
	String debugMode = cd.getValue("debugMode");
	
	String targetCode;
	if (regex != null && !regex.equals(""))
	{
		targetCode = sessionCourseId.replaceAll(regex, "");
	}
	else
	{
		targetCode = sessionCourseId;
	}

	aspireLink = aspireBaseUrl + "/" + targetKg.toLowerCase() + "/" + targetCode.toLowerCase()+"/lists";

	try  {
		URL u = new URL (aspireLink + ".json"); 
		HttpURLConnection huc =  (HttpURLConnection)  u.openConnection() ; 
		huc.setRequestMethod ("GET") ; 
		huc.connect(); 
		int code = huc.getResponseCode(); 
		if (debugMode.equals("true"))
		{
			String debugResponse = "";
			debugResponse = debugResponse + "<h3>Talis Aspire Linking Module</h3>";
			debugResponse = debugResponse + "<p><strong>You are currently running in debug mode</strong></p>";
			debugResponse = debugResponse + "<p>Debug mode should only be used for testing. To disable debug mode, refer to the Settings page for this Powerlink.</p>";
			debugResponse = debugResponse + "<table><tr><th>Property</th><th>Value</th></tr>";
			debugResponse = debugResponse + "<tr><td>Target Aspire Base URL</td><td>"+aspireBaseUrl+"</td></tr>";
			debugResponse = debugResponse + "<tr><td>Target knowledge grouping</td><td>"+targetKg+"</td></tr>";
			debugResponse = debugResponse + "<tr><td>Course ID</td><td>"+sessionCourseId+"</td></tr>";
			debugResponse = debugResponse + "<tr><td>Course ID regex</td>"+regex+"</td></tr>";
			debugResponse = debugResponse + "<tr><td>Target code</td><td>"+targetCode+"</td></tr>";
			debugResponse = debugResponse + "<tr><td>Aspire link</td><td>"+aspireLink+"</td></tr>";
			debugResponse = debugResponse + "<tr><td>HTTP response code</td><td>"+code+"</td></tr></table>";
			out.print(debugResponse);
		}
		else
		{
			if  (code  >= 200 && code <  300 ) {
				InputStreamReader in = new InputStreamReader((InputStream) huc.getContent());
				JSONObject jsonRoot = (JSONObject)new JSONParser().parse(in);
				JSONObject jsonModule = (JSONObject)jsonRoot.get(aspireBaseUrl + "/" + targetKg.toLowerCase() + "/" + targetCode.toLowerCase());
				JSONArray jsonLists  = (JSONArray)jsonModule.get("http://purl.org/vocab/resourcelist/schema#usesList");
				
				if(jsonLists == null || jsonLists.size() == 0) {
					out.println("<div class='noItems'>Sorry, there are no lists for " + targetKg.substring(0, targetKg.length() - 1).toLowerCase() + " " + targetCode + " yet.</div>");
				} else {
					out.println("<h3>Your reading lists:</h3><ul class='portletList'>");
					Iterator<JSONObject> iter = jsonLists.iterator();
					while(iter.hasNext()) {
						JSONObject jsonListEntry = iter.next();
						String listURI = (String)jsonListEntry.get("value");
						JSONObject jsonList = (JSONObject)jsonRoot.get(listURI);
											
						String listName = (String)((JSONObject)((JSONArray)jsonList.get("http://rdfs.org/sioc/spec/name")).get(0)).get("value");
						String listLastUpdated = (String)((JSONObject)((JSONArray)jsonList.get("http://purl.org/vocab/resourcelist/schema#lastUpdated")).get(0)).get("value");
						
						int listItems = 0;
						JSONArray containsArray = (JSONArray)jsonList.get("http://purl.org/vocab/resourcelist/schema#contains");
						for (int i = 0; i < containsArray.size(); i++) {
							String itemURI = (String)((JSONObject)containsArray.get(i)).get("value");
							if(itemURI.startsWith(aspireBaseUrl + "/items/"))
								listItems++;
						}
						String listUpdatedAgo = null;
						if (listLastUpdated != null || !listLastUpdated.isEmpty())
						{
							DateTimeFormatter parser = ISODateTimeFormat.dateTimeNoMillis();						
							PrettyTime p = new PrettyTime();
							listUpdatedAgo = p.format(parser.parseDateTime(listLastUpdated).toDate());
						}

						out.println("<li><a href='" + listURI + "' target='_blank'>" + listName + "</a><br />");
						out.print("(" + listItems + " items)");
						if (listLastUpdated != null || !listLastUpdated.isEmpty())
						{
						out.print(", last updated <span class='updated' title='" + listUpdatedAgo + "'>" + listUpdatedAgo + "</span>");
						}
						out.println("</li>");
					}
					out.println("</ul>");
				}
			}
			else if (code == 404)
			{
				out.println("<div class='noItems'>Sorry, there are no lists for " + targetKg.substring(0, targetKg.length() - 1).toLowerCase() + " " + targetCode + " yet.</div>");
			}
			else
			{
				out.println("<h3>Sorry, there was a problem connecting</h3>");
				out.println("<p>We received HTTP "+code+" from the reading list service</p>");
			}
			huc.disconnect();
		}
	}  
	catch  (IOException e)   
	{
		out.println("<h3>Sorry, there was a problem</h3>");
		out.println("<p>An IOException occurred</p><pre>"+e.getMessage()+"</pre>");
	} 
}
catch  (Exception e)   
{
	out.println("<h3>Sorry, there was a problem</h3>");
	out.println("<p>An Exception occurred</p><pre>"+e.getMessage()+"</pre>");
}  
	
%>
</bbData:context>